"""
@Author  : 康帅
@Time    : 2021/8/3 15:19
@Function: 力扣：2.两数相加(中等)
"""


class ListNode:
    def __init__(self, val=0):
        self.val = val
        self.next = None


class Solution(object):

    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        会出现以下四种情况：
            1.l1不存在l2存在
            2.l2不存在l1存在
            3.l1+l2需要留余进整
            4.l1与l2不等长
            5.l2与l1不等长
            6.结果最后一位l1+l2刚好等于10
        """
        # 情况一，情况二
        if l1 is None:
            return l2
        if l2 is None:
            return l1

        dummy = ListNode(0)
        # 当前值
        p = dummy
        # next值
        carry = 0

        # 情况三
        while l1 and l2:
            p.next = ListNode((l1.val + l2.val + carry) % 10)
            carry = (l1.val + l2.val + carry) // 10
            l1 = l1.next
            l2 = l2.next
            p = p.next

        # 情况四
        if l2:
            while l2:
                p.next = ListNode((l2.val + carry) % 10)
                carry = (l2.val + carry) // 10
                l2 = l2.next
                p = p.next

        # 情况五
        if l1:
            while l1:
                p.next = ListNode((l1.val + carry) % 10)
                carry = (l1.val + carry) // 10
                l1 = l1.next
                p = p.next

        # 情况六
        if carry == 1:
            p.next = ListNode(1)

        return dummy.next
